const http = require('http');

const server = http.createServer();

let items = [
    {id: 1, name: '11111'},
    {id: 2, name: '22222'},
    {id: 3, name: '33333'},
    {id: 4, name: '44444'},
    {id: 5, name: '55555'},
    {id: 6, name: '66666'},
    {id: 7, name: '77777'},
    {id: 8, name: '88888'}
]

server.on('request', async (req, res) => {
    res.setHeader('Content-Type', 'text/html;charset=utf-8');
    // 当前请求的 URL 就是一组数据，服务端可以根据不同的 URL 数据做不同事情，返回不同的结果
    if (req.url == '/') {
        res.end('index');
    }

    if (req.url == '/register') {
        res.end('register');
    }

    // 动态路由
    // /item/12 => dyRouter.groups.id = 12
    let dyRouter = /\/item\/(?<id>\d+)/gi.exec(req.url);
    if (dyRouter) {
        let { id } = dyRouter.groups;

        res.end(`当前传入的id: ${id}`);
    }


    // http://localhost:8888/items?page=1&limit=5
    if (req.url.startsWith('/items')) {

        const u = new URL(`${req.headers.host}${req.url}`);
        // console.log(u);
        const query = u.searchParams;
        console.log(`page: ${query.get('page')} , limit: ${query.get('limit')}`);
        let page = Number(query.get('page')) || 1;
        let limit = Number(query.get('limit')) || 5;

        // 1 0
        // 2 3
        let start = (page - 1) * limit;
        let end = start + limit;
        console.log(start, end);

        let resItems = items.filter((t, i) => i >= start && i < end);

        res.end(JSON.stringify(resItems));
    }

});

server.listen(8888);
